package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.iot.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 设备属性数据Service业务层处理
 * 
 * @author Jiagege
 * @date 2025-08-03
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询设备属性数据
     * 
     * @param id 设备属性数据主键
     * @return 设备属性数据
     */
    @Override
    public DeviceData selectDeviceDataById(Integer id)
    {
        return getById(id);
    }

    /**
     * 查询设备属性数据列表
     * 
     * @param deviceData 设备属性数据
     * @return 设备属性数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备属性数据
     * 
     * @param deviceData 设备属性数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备属性数据
     * 
     * @param deviceData 设备属性数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备属性数据
     * 
     * @param ids 需要删除的设备属性数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Integer[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备属性数据信息
     * 
     * @param id 设备属性数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Integer id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量新增设备属性数据
     * @param data
     */
    @Override
    public void saveBatchDeviceData(IotMsgNotifyData data) {
        //查询设备id    iot_id
        String iotId = data.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtils.isEmpty(device)){
            log.error("设备不存在,iotId:{}",iotId);
            throw new BaseException("未获取到设备信息,请重新核验.");
        }
        //批量保存设备属性数据
        List<DeviceData> list = new ArrayList<>();
        data.getBody().getServices().forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            if(ObjectUtils.isEmpty(properties)){
                log.error("设备属性数据为空,properties:{}",properties);
                return;
            }
            String time = service.getEventTime();
            //处理时间字符串---不带毫秒值
            LocalDateTime eventTimeStr = LocalDateTimeUtil.parse(time, "yyyyMMdd'T'HHmmss'Z'");
            //转换时区至东八区
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeStr);
            properties.forEach((k,v)->{
                DeviceData deviceData = new DeviceData();
                deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setIotId(iotId);
                deviceData.setAlarmTime(eventTime);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                list.add(deviceData);
            });
            saveBatch(list);


            redisTemplate.opsForHash().put(Constants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(list));

        });



    }
}
